/*******************************************************************************
 * Copyright 2011-2012 Dik Grapendaal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package sh.grapendaal.tsuushin.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.SchemaFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.xml.sax.SAXException;

import sh.grapendaal.tsuushin.binding.config.Bot;
import sh.grapendaal.tsuushin.binding.config.Channel;
import sh.grapendaal.tsuushin.binding.config.IRCBot;
import sh.grapendaal.tsuushin.binding.config.Network;
import sh.grapendaal.tsuushin.binding.config.Owner;
import sh.grapendaal.tsuushin.binding.config.Permission;
import sh.grapendaal.tsuushin.binding.config.Server;
import sh.grapendaal.tsuushin.core.IrcBot;
import sh.grapendaal.tsuushin.service.BotService;
import sh.grapendaal.tsuushin.service.ConfigService;
import sh.grapendaal.tsuushin.service.NetworkService;
import sh.grapendaal.tsuushin.service.PermissionService;
import sh.grapendaal.tsuushin.tracking.User;

@Service
public class ConfigServiceImpl implements ConfigService {
	private static final Logger logger = LoggerFactory.getLogger(ConfigServiceImpl.class);

	@Value("${classpath:ircbotConfiguration.xsd}")
	private Resource configSchema;

	@Autowired
	private NetworkService networkService;

	@Autowired
	private BotService botService;

	@Autowired
	private PermissionService permissionService;

	private boolean testEnvironment = false;
	private String relativeWorkingDir = "";
	private IRCBot configuration;

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean isTestEnvironment() {
		return testEnvironment;
	}

	/**
	 * Sets whether we are running in a test environment.
	 * 
	 * @param testEnvironment
	 *            Whether we are running in a test environment.
	 */
	public void setTestEnvironment(boolean testEnvironment) {
		this.testEnvironment = testEnvironment;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public String getRelativeWorkingDirectory() {
		return relativeWorkingDir;
	}

	/**
	 * Sets the relative working directory. For more information see
	 * {@link ConfigService.getRelativeWorkingDirectory}.
	 * 
	 * @param directory
	 *            The directory to set.
	 */
	public void setRelativeWorkingDirectory(String directory) {
		this.relativeWorkingDir = directory;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IRCBot getConfiguration() {
		return configuration;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void loadConfiguration(File configurationFile) throws SAXException, JAXBException, IOException {
		configuration = this.parse(configurationFile);
		logger.debug("Parsed configuration: {}", configuration);
		
		permissionService.registerPermission(PermissionService.PERMISSION_BOT_OWNER);

		for (Network network : configuration.getNetwork()) {
			for (Server server : network.getServer()) {
				networkService.addServer(network.getName(), server.getAddress(), server.getPort());
			}
		}

		for (Bot bot : configuration.getBot()) {
			IrcBot createdBot = botService.createBot(bot.getNickname(), networkService.getNetwork(bot.getNetwork()));
			createdBot.setUsername(bot.getUsername());
			createdBot.setRealname(bot.getRealname());
			for (Channel channel : bot.getChannel()) {
				createdBot.addChannel(channel.getName(), channel.getPassword());
			}

			for (Owner owner : bot.getOwner()) {
				User ownerUser = User.parse(owner.getUsermask());
				permissionService.addUser(ownerUser, owner.getPassword());
				for (Permission permission : owner.getPermission()) {
					permissionService.grantPermission(ownerUser, permission.getName());
				}
				
				// Double check whether we have the "owner" permission.
				if (!permissionService.isBotOwner(ownerUser)) {
					permissionService.grantPermission(ownerUser, PermissionService.PERMISSION_BOT_OWNER);
				}
			}
		}
	}

	/**
	 * Parses the XML configuration file and returns the complete document as a
	 * tree of Java objects. This method assumes that the file given is a IRCBot
	 * configuration file.
	 * 
	 * @param xmlFile
	 *            The XML file to parse.
	 * @return The XML document as a tree of Java objects.
	 * @throws JAXBException
	 *             If any unexpected errors occur while unmarshalling.
	 * @throws SAXException
	 *             If a SAX error occurs during parsing of the XSD.
	 * @throws IOException
	 *             If the XML file was not found or the XSD could not be opened.
	 */
	@SuppressWarnings("unchecked")
	private IRCBot parse(File xmlFile) throws JAXBException, SAXException, IOException {
		SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
		JAXBContext context = JAXBContext.newInstance(IRCBot.class.getPackage().getName());
		Unmarshaller unmarshaller = context.createUnmarshaller();

		unmarshaller.setSchema(schemaFactory.newSchema(configSchema.getURL()));
		JAXBElement<IRCBot> parsed;
		try {
			parsed = (JAXBElement<IRCBot>) unmarshaller.unmarshal(new FileInputStream(xmlFile));
		} catch (JAXBException e) {
			if (e.getLinkedException() instanceof SAXException) {
				// Throw the SAXException to prevent unnecessary stack traces
				// which make the actual error harder to find.
				throw (SAXException) e.getLinkedException();
			}

			throw e;
		}
		return parsed.getValue();
	}
}
